import { isEmpty } from 'lodash-es'
import { useEffect, useState } from 'react'

import { hospitalAndAreaTreeApi } from '@/api/pcs/pcsHospital'
import { createInpatientWardApi, updateInpatientWardApi } from '@/api/pcs/pcsInpatientWard'
import AekForm from '@/components/AekForm'
import AekModal, { PromiseThen } from '@/components/AekModal'
import { requestWithTry } from '@/utils/request'

const EditModal = ({ row = {} }) => {
  const [form] = AekForm.useForm()
  const { id } = row

  const hospitalId = AekForm.useWatch('hospitalId', form)

  const [hospitalAndAreaTree, setHospitalAndAreaTree] = useState([])
  const [areaInfos, setAreaInfos] = useState([])

  const getHospitalAndAreaTree = async () => {
    const { data } = await requestWithTry(hospitalAndAreaTreeApi)
    setHospitalAndAreaTree(data)
  }

  useEffect(() => {
    if (!hospitalId || isEmpty(hospitalAndAreaTree)) return
    const { areaInfos } = hospitalAndAreaTree.find(({ id }) => id === hospitalId)
    setAreaInfos(areaInfos)
  }, [hospitalId, hospitalAndAreaTree])

  useEffect(() => {
    if (!row.hospitalId) return
    form.setFieldsValue({
      name: row.name,
      hospitalId: row.hospitalId,
      areaId: row.areaId,
    })
  }, [row.hospitalId])

  useEffect(() => {
    getHospitalAndAreaTree()
  }, [])

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData = [
    {
      field: 'name',
      label: '病区名称',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: { name: 'Input' },
    },
    {
      field: 'hospitalId',
      label: '所属医院',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekSelect',
        props: {
          options: hospitalAndAreaTree,
          onChange: value => {
            const { areaInfos } = hospitalAndAreaTree.find(({ id }) => id === value)
            form.setFieldsValue({
              areaId: undefined,
            })
            if (areaInfos.length === 1) {
              form.setFieldsValue({
                areaId: areaInfos[0].id,
              })
            }
          },
        },
      },
    },
    {
      field: 'areaId',
      label: '所属院区',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekSelect',
        props: {
          options: areaInfos,
        },
      },
    },
  ]

  const onOk = async () => {
    const values = await form.validateFields()
    const params = {
      id,
      ...values,
    }
    await requestWithTry(id ? updateInpatientWardApi : createInpatientWardApi, params)
  }
  return (
    <AekModal title={id ? '编辑' : '新增'} width={500} onOk={onOk}>
      <AekForm form={form} formData={formData} />
    </AekModal>
  )
}

EditModal.PromiseThen = PromiseThen

export default EditModal
